package com.yuantu.judiciary.serviceimpl;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.yuantu.judicial.model.enums.TempExceptionEnum;
import com.yuantu.judiciary.dao.ITempMinghangTestDao;
import com.yuantu.judiciary.model.domain.TempMinhangTestDO;
import com.yuantu.judiciary.service.IMinHangApiService;
import com.yuantu.judiciary.utils.AssertUtil;
import com.yuantu.judiciary.utils.RedisUtil;
import com.yuantu.judiciary.utils.UrlUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Service
@RequiredArgsConstructor
@Slf4j
public class MinHangApiServiceImpl implements IMinHangApiService {

    private final ITempMinghangTestDao tempMinghangTestDao;

    @Autowired
    private RedisUtil redisUtil;
    @Override
    public Boolean idNumberVerify(String name, String idNumber) {
        String appKey = "qW89tW7S9qpQa4s9";
        String appSecret = "eJNVjU5d7XVDuQ4AqcRGKHOa";
        String ticket = UUID.randomUUID().toString().toUpperCase();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String str = "appKey=" + appKey +"&appSecret="+ appSecret +
                "&ticket="+ ticket + "&timestamp="+timestamp+"&version=3";
        String sign = UrlUtil.md5ByHex(str);
        String url = "http://open.caifbigdata.com/api/person/idCardBaseCheckV3?v=3";
        String body = "{\n" +
                            "\"appKey\":\""+ appKey +"\",\n" +
                            "\"body\":{\n" +
                                "\"name\":\""+ name +"\",\n" +
                                "\"idcard\":\""+ idNumber +"\"\n" +
                            "},\n" +
                            "\"sign\":\""+ sign +"\",\n" +
                            "\"ticket\":\""+ ticket + "\",\n" +
                            "\"timestamp\":"+ timestamp +",\n" +
                            "\"version\":\"3\"\n" +
                        "}";
        String res = HttpUtil.post(url, body);
        String result = JSONObject.parseObject(res).
                getJSONObject("body").
                getJSONObject("data").getString("result");
        return result.equals("1");
    }

    /**
     * 司法风险查询方法
     * @param idCard 查询身份证，支持MD5，格式为MD5:xxxxx(md5值小写)
     * @param name 查询姓名，支持MD5，格式为MD5:xxxxx(md5值小写)
     * @return 司法风险查询结果列表
     */
    @Override
    public Integer judicialRiskQuery(String idCard, String name) {
        AssertUtil.assertTrue(IdcardUtil.isValidCard(idCard), TempExceptionEnum.WRONG_ID_CARD);
        String regex = "^[\\u4e00-\\u9fa5]{2,15}$";
        AssertUtil.assertTrue(ReUtil.isMatch(regex, name), TempExceptionEnum.WRONG_NAME);
        if(redisUtil.hasKey(idCard)){
            return Integer.valueOf(redisUtil.get(idCard));
        }
        TempMinhangTestDO tempMinhangTestDOInDb = tempMinghangTestDao.findFirstByIdNumber(idCard);
        if(!ObjectUtils.isEmpty(tempMinhangTestDOInDb)){
            String result  = tempMinhangTestDOInDb.getResult();
            JSONObject data = JSONObject.parseObject(result).
                    getJSONObject("body").
                    getJSONObject("data");
            redisUtil.set(idCard, data.getInteger("result").toString());
            return data.getInteger("result");
        }
//        AssertUtil.assertTrue(tempMinghangTestDao.count() <=5000, TempExceptionEnum.OVER_COUNT);
        String appKey = "qW89tW7S9qpQa4s9";
        String appSecret = "eJNVjU5d7XVDuQ4AqcRGKHOa";
        String ticket = UUID.randomUUID().toString().toUpperCase();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String str = "appKey=" + appKey +"&appSecret="+ appSecret +
                "&ticket="+ ticket + "&timestamp="+timestamp+"&version=1";
        String sign = UrlUtil.md5ByHex(str);
        String url = "http://open.caifbigdata.com/api/personal/vast-risk?v=1";
        LocalDate today = LocalDate.now();
        LocalDate twoDaysLater = today.plusDays(2);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String todayStr = today.format(formatter);
        String twoDaysLaterStr = twoDaysLater.format(formatter);

        String queryAuth = "authed:" + todayStr + "-" + twoDaysLaterStr;
        String reqNo = UUID.randomUUID().toString().replace("-","");
        String body = "{\n" +
                "\"appKey\":\""+ appKey +"\",\n" +
                "\"body\":{\n" +
                "\"name\":\""+ name +"\",\n" +
                "\"idCard\":\""+ idCard +"\",\n" +
                "\"queryAuth\":\""+ queryAuth +"\",\n" +
                "\"reqNo\":\""+ reqNo +"\"\n" +
                "},\n" +
                "\"sign\":\""+ sign +"\",\n" +
                "\"ticket\":\""+ ticket + "\",\n" +
                "\"timestamp\":"+ timestamp +",\n" +
                "\"version\":\"1\"\n" +
                "}";
        String res = HttpUtil.post(url, body);

        TempMinhangTestDO tempMinhangTestDO = new TempMinhangTestDO();
        tempMinhangTestDO.setIdNumber(idCard);
        tempMinhangTestDO.setName(name);
        tempMinhangTestDO.setCreateTime(new Timestamp(System.currentTimeMillis()));
        tempMinhangTestDO.setResult(res);
        tempMinghangTestDao.save(tempMinhangTestDO);

        JSONObject data = JSONObject.parseObject(res).
                getJSONObject("body").
                getJSONObject("data");

        redisUtil.set(idCard, data.getInteger("result").toString());
        return data.getInteger("result");
    }
}

